package com.worldcup.service.help;

import com.worldcup.model.Travel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author duwan.zq
 * @date 2018/05/24
 */
@Component
public class TimeMatch implements TravelMatch{

    private static final Logger logger = LoggerFactory.getLogger(TimeMatch.class);

    private final static DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public boolean isMatch(List<Travel> travels, List<Travel> refTravels) {
        if(CollectionUtils.isEmpty(travels)){
            return false;
        }
        if(CollectionUtils.isEmpty(refTravels)){
            return false;
        }
        LocalDate earlyStart = null;
        LocalDate lastEnd = null;
        for(Travel travel : travels){
            LocalDate start = LocalDate.parse(travel.getStartDate(), DATE_FORMATTER);
            LocalDate end =  LocalDate.parse(travel.getEndDate(), DATE_FORMATTER);
            if(earlyStart == null || start.isBefore(earlyStart)){
                earlyStart = start;
            }
            if(lastEnd == null || end.isAfter(lastEnd)){
                lastEnd = end;
            }
        }

        LocalDate refEarlyStart = null;
        LocalDate refLastEnd = null;
        for(Travel refTravel : refTravels){
            LocalDate refStart = LocalDate.parse(refTravel.getStartDate(), DATE_FORMATTER);
            LocalDate refEnd =  LocalDate.parse(refTravel.getEndDate(), DATE_FORMATTER);
            if(refEarlyStart == null || refStart.isBefore(refEarlyStart)){
                refEarlyStart = refStart;
            }
            if(logger.isDebugEnabled()){
                logger.debug(" ");
            }
            if(refLastEnd == null || refEnd.isAfter(refLastEnd)){
                refLastEnd = refEnd;
            }
        }

        if(lastEnd.isBefore(refEarlyStart) || refLastEnd.isBefore(earlyStart)){
            return false;
        }

        return true;
    }
}
